﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using Sinacor.Infra.Service.Common;
using Sinacor.Infra.Common.Exceptions;
using Sinacor.Infra.Service.ExceptionHandling;
using Sinacor.Servico.Bovespa.Corretagem.BusinessEntity;
using Sinacor.Infra.Service.Validation;


namespace Sinacor.Servico.Bovespa.Corretagem.BusinessLogic
{
    /// <summary>
    /// Taxa
    /// </summary>
    public class Taxa : BaseBusinessLogic
    {
        #region Constantes de Erro
        private const int consultartaxas_request = 109074;
        private const int filtrotaxas_request = 109069;
        private const int filtrotaxasDataInicio_request = 109071;
        private const int filtrotaxasPeriodo_request = 109070;

        private const int consultartaxas_natureza_operacao = 109069;
        private const int consultartaxas_periodo_invalido = 109070;
        private const int consultartaxas_periodo_nulo = 109071;

        private const int excluirtaxa_request_nulo = 109072;
        private const int excluirtaxa_data_calendario = 109068;

        private const int incluirtaxa_request_nulo = 109066;

        private const int validataxa_naturezaoperacao_nulo = 109052;
        private const int validataxa_codigobolsa_nulo = 109053;
        private const int validataxa_mercado_nulo = 109054;
        private const int validataxa_mercadoorigem_nulo = 109055;
        private const int validataxa_operacao_nulo = 109056;
        private const int validataxa_papel_nulo = 109058;
        private const int validataxa_cliente_nulo = 109059;
        private const int validataxa_liquidacao_nulo = 109060;
        private const int validataxa_periodo_datainicial_nulo = 109061;
        private const int validataxa_periodo_datafinal_nulo = 109062;
        private const int validartaxa_periodo_datainicio_calendario = 109063;
        private const int validartaxa_valida_taxa_cadastrada = 109067;
        private const int validartaxa_periodo_datainicio_menor_periodo_data_fim = 109064;
        private const int validartaxa_taxa_identificadores = 109065;
        

        #endregion

        #region Construtor

        private Sinacor.Servico.Bovespa.Corretagem.ResourceAccess.Taxa _taxa;
        /// <summary>
        /// Taxa
        /// </summary>
        public Taxa()
            : base()
        {
            _taxa = new Sinacor.Servico.Bovespa.Corretagem.ResourceAccess.Taxa();         
        }
        #endregion

        #region AlterarTaxa
        /// <summary>
        /// AlterarTaxa
        /// </summary>
        /// <param name="request"></param>
        public void AlterarTaxa(BusinessEntity.Taxa request)
        {
            ValidaAlterarTaxas(request); 
            _taxa.AlterarTaxa(request); 
        }
        
        #endregion

        #region AlterarTaxas
        /// <summary>
        /// Alterar Taxas
        /// </summary>
        /// <param name="requests"></param>
        public void AlterarTaxas(List<BusinessEntity.Taxa> requests)
        {
            foreach (var item in requests)
	        {
                 ValidaAlterarTaxas(item); 
		         _taxa.AlterarTaxa(item); 
	        }
            
        }
        /// <summary>
        /// Validar Taxas
        /// </summary>
        /// <param name="request"></param>
        private void ValidaAlterarTaxas(BusinessEntity.Taxa request)
        {
            SinacorValidation validation = new SinacorValidation();
            validation.Validate<BusinessEntity.Taxa>((request),"Alteracao"); 
        }
        #endregion

        #region ConsultarTaxas

        /// <summary>
        /// ConsultarTaxas
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public List<BusinessEntity.Taxa> ConsultarTaxas(BusinessEntity.Parameter.FiltroTaxa request)
        {
            if(request == null)
                throw new BusinessException(consultartaxas_request);

            #region Validar Filtro
            // Excluído por Thiago Dyna - 31/03/09 19:45

            #region Natureza Operação
            // Alterado por Thiago Dyna - 31/03/09 19:45
            if (request.NaturezaOperacao != null && 
                string.IsNullOrEmpty(request.Bolsa) &&
                string.IsNullOrEmpty(request.Mercado) &&
                string.IsNullOrEmpty(request.MercadoOrigem) &&
                request.Periodo == null
                )
                throw new BusinessException(filtrotaxas_request);

            #endregion

            #region Periodo

            if (request.Periodo != null)
            {
                // Adicionado por Thiago Dyna - 31/03/09 19:45
                if (request.Periodo.DataInicial.HasValue && request.Periodo.DataFinal.HasValue)
                {
                    if (request.Periodo.DataInicial.Value > request.Periodo.DataFinal.Value)
                        throw new BusinessException(filtrotaxasPeriodo_request);
                }
                else
                {
                    if (request.Periodo.DataInicial == null && request.Periodo.DataFinal != null)
                        throw new BusinessException(consultartaxas_periodo_nulo);
                }


                // Excluído por Thiago Dyna - 31/03/09 19:45
            }

            #endregion

            // Excluído por Thiago Dyna - 31/03/09 19:45
            #endregion

            List<BusinessEntity.Taxa> listataxa = _taxa.ConsultarTaxas(request);

            return listataxa;
        }
        #endregion

        #region ObterTaxa
        /// <summary>
        /// ObterTaxa
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public BusinessEntity.Taxa ObterTaxas(BusinessEntity.ChaveTaxa request)
        {
            BusinessEntity.Taxa taxa = _taxa.ObterTaxas(request);
            return taxa;
        }
        #endregion

        #region ExcluirTaxa
        /// <summary>
        /// Excluir Taxa
        /// </summary>
        /// <param name="request"></param>
        public void ExcluirTaxa(BusinessEntity.ChaveTaxa request)
        {
            #region Parametro entrada nulo

            if (request == null)
                throw new BusinessException(excluirtaxa_request_nulo);

            #endregion

            #region ObterTaxa

            BusinessEntity.Taxa taxa = this.ObterTaxas(request);

            #endregion

            #region Valida Data periodo Final

            Calendario.BusinessLogic.Calendario calendario = new Calendario.BusinessLogic.Calendario();

            DateTime datacalendario = calendario.ObterUltimaDataCalendario();

            if (taxa.Periodo.DataFinal < datacalendario)
                throw new BusinessException(excluirtaxa_data_calendario);

            #endregion

            _taxa.ExcluirTaxa(request);

        }

        #endregion

        #region ExcluirTaxas
        /// <summary>
        /// ExcluirTaxas
        /// </summary>
        /// <param name="request"></param>
        public void ExcluirTaxas(List<BusinessEntity.ChaveTaxa> request)
        {
            //Implementar regra ver o EA
            foreach (var item in request)
            {
                this.ExcluirTaxa(item);
            }            
        }
        #endregion

        #region ExecutarTransacoes
        /// <summary>
        /// ExecutarTransacoes
        /// </summary>
        /// <param name="listaInclusao"></param>
        /// <param name="listaExclusao"></param>
        /// <param name="listaAlteracao"></param>
        public void ExecutarTransacoes(List<BusinessEntity.Taxa> listaInclusao, List<BusinessEntity.ChaveTaxa> listaExclusao, List<BusinessEntity.Taxa> listaAlteracao)
        {
            //Implementar regra ver o EA
            foreach (var item in listaInclusao)
            {
                if (item == null)
                    throw new BusinessException(incluirtaxa_request_nulo);

                if (ValidarTaxa(item))
                    _taxa.IncluirTaxa(item);
            }

            foreach (var item in listaExclusao)
            {
                _taxa.ExcluirTaxa(item);
            }

            foreach (var item in listaAlteracao)
            {
                _taxa.AlterarTaxa(item);
            }
        }
        #endregion

        #region IncluirTaxa
        /// <summary>
        /// IncluirTaxa
        /// </summary>
        /// <param name="request"></param>
        public void IncluirTaxa(BusinessEntity.Taxa request)
        {
            #region Parametro entrada nulo

            if (request == null)
                throw new BusinessException(incluirtaxa_request_nulo);

            #endregion

            if (ValidarTaxa(request))
                _taxa.IncluirTaxa(request);
        }
        #endregion

        #region IncluirTaxas
        /// <summary>
        /// IncluirTaxas
        /// </summary>
        /// <param name="request"></param>
        public void IncluirTaxas(List<BusinessEntity.Taxa> request)
        {
            foreach (var item in request)
            {
                if (ValidarTaxa(item))
                    _taxa.IncluirTaxa(item);                
            }            
        }
        #endregion

        #region ValidarExistenciaTaxa
        /// <summary>
        /// VerificarExistenciaTaxa
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private bool VerificarExistenciaTaxa(BusinessEntity.Taxa request)
        {
            bool retorno;

            retorno = _taxa.VerificarExistenciaTaxa(request);

            return retorno;
        }
        #endregion

        #region ValidarTaxa
        /// <summary>
        /// ValidarTaxa
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private bool ValidarTaxa(BusinessEntity.Taxa request)
        {   
            SinacorValidation validation = new SinacorValidation();
            validation.Validate<BusinessEntity.Taxa>(request); 
            
            Calendario.BusinessLogic.Calendario calendario = new Calendario.BusinessLogic.Calendario();

            DateTime datacalendario = calendario.ObterUltimaDataCalendario();

            #region Valida Data Periodo Inicial

            if (request.Periodo.DataInicial < datacalendario)            
                throw new BusinessException(validartaxa_periodo_datainicio_calendario);
            #endregion

            #region Verifica taxa Cadastrada
            
            bool validarexistenciataxa = VerificarExistenciaTaxa(request);

            if (validarexistenciataxa)           
                throw new BusinessException(validartaxa_valida_taxa_cadastrada);
                
            #endregion

            #region Valida Data Periodo Final

            if (request.Periodo.DataInicial > request.Periodo.DataFinal)            
                throw new BusinessException(validartaxa_periodo_datainicio_menor_periodo_data_fim);
                
            #endregion

            #region Valida Taxa identificadores e que o período conflite com o novo registro.

            bool verificarconflitoperiodo = VerificarConflitoPeriodo(request);

            if (verificarconflitoperiodo)
                throw new BusinessException(validartaxa_taxa_identificadores);
           
            #endregion

            return true;
        }
        
        #endregion

        #region VerificarConflitoPeriodo
        /// <summary>
        /// VerificarConflitoPeriodo
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public bool VerificarConflitoPeriodo(BusinessEntity.Taxa request)
        {
            bool retorno = _taxa.VerificarConflitoPeriodo(request);
            
            return retorno;
        }
        #endregion
    }
}
